package com.test.schoolhelper.ui.activity;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;

import com.test.schoolhelper.R;
import com.test.schoolhelper.base.BaseActivity;
import com.test.schoolhelper.databinding.ActivityAddUserBinding;
import com.test.schoolhelper.db.DbUserController;
import com.test.schoolhelper.entity.User;
import com.test.schoolhelper.event.UserEvent;
import com.test.schoolhelper.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

// TODO: 2024/6/1 添加联系人
public class AddUserActivity extends BaseActivity<ActivityAddUserBinding> implements View.OnClickListener {

    @Override
    protected void initClick() {
        super.initClick();
        getBinding().ivBack.setOnClickListener(this);
        getBinding().tvSave.setOnClickListener(this);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_add_user;
    }

    @Override
    protected ActivityAddUserBinding onCreateViewBinding(@NonNull LayoutInflater layoutInflater) {
        return ActivityAddUserBinding.inflate(layoutInflater);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_save:
                save();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private void save() {
        String name = getBinding().etName.getText().toString();
        String phone = getBinding().etPhone.getText().toString();
        if (name.isEmpty() || phone.isEmpty()){
            ToastUtils.getInstance().show(this, "姓名和电话不能为空！");
            return;
        }
        String company = getBinding().etCompany.getText().toString();
        String address = getBinding().etAddress.getText().toString();

        User user = new User(name, phone, company,address);
        DbUserController.getInstance(this).insertOrReplace(user);
        EventBus.getDefault().post(new UserEvent());
        new Handler().postDelayed(() -> {
            ToastUtils.getInstance().show(this, "保存成功！");
            finish();
        },500);
    }
}